package com.alison;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import java.util.Collection;
import java.util.LinkedHashSet;

// 自定义分库算法类，实现StandardShardingAlgorithm接口用于精确分片（比如按照某个字段值路由到具体库）
// 这里假设按照用户ID的奇偶性分库，偶数到库0，奇数到库1，仅为示例，实际场景按需设计
public class CustomDatabaseShardingAlgorithm implements StandardShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        long value = shardingValue.getValue();
        // 根据具体规则选择库，这里简单以奇偶判断
        if (value % 2 == 0) {
            return "ds_2";
        } else {
            return "ds_1";
        }
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Long> shardingValue) {
        Collection<String> result = new LinkedHashSet<>();
        // 处理范围分片情况（比如 BETWEEN... AND...语句涉及的分片逻辑），示例简化，实际按需处理更复杂逻辑
        for (long i = shardingValue.getValueRange().lowerEndpoint(); i <= shardingValue.getValueRange().upperEndpoint(); i++) {
            if (i % 2 == 0) {
                result.add("ds_2");
            } else {
                result.add("ds_1");
            }
        }
        return result;
    }

    @Override
    public void init() {
        // 初始化方法，可以从配置Properties读取自定义配置参数等，这里示例暂不做具体处理
    }

    @Override
    public String getType() {
        return "CUSTOM_DATABASE_SHARDING";
    }
}